// import Vue from 'vue';
// import { environment } from './until_new.js';
// import config from '../../src/config/index.js';

const baseUrl2 = environment() ? "https://webv1.whoisamy.shop/" :"https://test.chathot.me/";
// var baseUrl = environment() ? "https://web.starchat.live" : "http://test.web.chathot.me";

// const baseUrl = config.baseUrl;
const API2 = {
    api_request: baseUrl2 + "app/index.php?i=6&c=entry&m=db_play&do=api_request"
  }
const $ = (function () { 
  return {
    ajax2: function ({ type, url, data, isAsync, success, error }) {
      if (!url) { 
        console.error('请输入请求地址')
        return;
      }
      var xhr = new XMLHttpRequest();
      var query = [], queryData;
      for (var key in data) {
        query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
      }
      queryData = query.join('&');
      if (type == 'GET') {
        if (url.indexOf('?') > -1) {
          url = url + '&' + queryData
        } else {
          url = url + '?' + queryData
        }
      }
      xhr.open(type || 'GET', url, isAsync || true);
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200 && success) { 
          try {
            success(JSON.parse(xhr.responseText)); 
          } catch {
            success({
              code: 400,
              data: {},
              message: 'error',
            })
          }
        }
        else if (xhr.readyState == 4 && xhr.status == 500) {
          error(xhr)          
        }
      }
      if (type == 'POST') {
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        xhr.send(queryData)
      } else {
        xhr.send()
      }
    }
  }
})();

const _localData = {
  loadingNum: 0,
  loadingToast: '',
  loadingTime: 300,
};

/**
 * otherParams 其他参数
 *  customStatus: 走success时是否自定义判断状态来做其他提示或逻辑，默认false不需要
 *  hideLoading: true 不loading
*/
function ajax2 (method, param, otherParams = {}, url = API2.api_request) {
  return new Promise(function (resolve, reject) {
    if (!otherParams.hideLoading) {
      handleLoading('show');
    }
    // let toastWarn = Vue.prototype.$VueGlobal.Toast;
    // toastWarn.allowMultiple();
    const getReqStart = new Date().getTime();
    $.ajax2({
      type: method,
      url,
      data: param,
      success: function (data) {
        const getReqEnd = new Date().getTime();
        // 请求太快时延迟loading消失使其看起来不会一闪一闪
        // if (getReqEnd - getReqStart < _localData.loadingTime) {
        //   setTimeout(() => {
        //     if (!otherParams.hideLoading) {
        //       handleLoading('hide');
        //     }
        //   }, _localData.loadingTime - (getReqEnd - getReqStart))
        // } else {
        //   if (!otherParams.hideLoading) {
        //     handleLoading('hide');
        //   }
        // }

        // if (!otherParams.customStatus) {
        //   if (handleStatus(data)) {
        //     reject(data)
        //   } else {
        //     resolve(data);
        //   }
        // } else {
        //   resolve(data);
        // }

        setTimeout(() => {
          if (!otherParams.hideLoading) {
            handleLoading('hide');
          }
          if (!otherParams.customStatus) {
            if (handleStatus(data)) {
              reject(data)
            } else {
              resolve(data);
            }
          } else {
            resolve(data);
          }          
        }, _localData.loadingTime - (getReqEnd - getReqStart))

      },
      error: function (error) {
        console.log(error)
        if (!otherParams.hideLoading) {
          handleLoading('hide');
        }
        // toastWarn({
        //   message: 'Request failed',
        // });
        reject(error)
      }
    });
  });
};
/*
  status: show展示或者隐藏hide
*/
function handleLoading(status) {
  if (status === 'show') {
    // if (_localData.loadingNum === 0) {
    //   const Toast = _localData.loadingToast = Vue.prototype.$VueGlobal.Toast;
    //   Toast.loading({
    //     duration: 0,
    //     forbidClick: true,
    //   })
    // }
    _localData.loadingNum += 1;
    return;
  }
  if (status === 'hide') {
    _localData.loadingNum -= 1;
    if (_localData.loadingNum === 0) {
      _localData.loadingToast && _localData.loadingToast.clear({
        clearAll: false,
      });
    }
  }
}

function handleStatus(data) {
  // const Toast = Vue.prototype.$VueGlobal.Toast;
  if (Number(data.status) == 200) return false;
  else {
    // Toast({
    //   message: data.info,
    // });
    return true;
  }
}
